package com.pai4j.user.service;


import com.alibaba.nacos.common.utils.CollectionUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import com.pai4j.common.enums.RedisKeyEnum;
import com.pai4j.common.enums.RoleCodeEnum;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.common.util.RedisUtil;
import com.pai4j.domain.vo.response.subjectaccount.SubjectAccountVO;
import com.pai4j.user.repository.dao.IUserDAO;
import com.pai4j.user.repository.entity.UserEntity;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SubjectAccountService {

    @Resource
    private IUserDAO userDAO;

    @Resource
    private RedisUtil redisUtil;


    /**
     * 查询全部专题列表
     *
     * @return
     */
    public List<SubjectAccountVO> getSubjectAccountListFromCache() {
        String key = RedisKeyEnum.SUBJECT_ACCOUNT_LIST_CACHE.getKey();
        String cache = redisUtil.get(key);
        if (StringUtils.isNotBlank(cache)) {
            return JsonUtil.fromJson(cache, new TypeReference<List<SubjectAccountVO>>() { });
        }
        return this.refreshSubjectAccountListCache();
    }

    /**
     * 刷新专题列表缓存
     *
     * @return
     */
    public List<SubjectAccountVO> refreshSubjectAccountListCache() {
        String key = RedisKeyEnum.SUBJECT_ACCOUNT_LIST_CACHE.getKey();
        List<UserEntity> list = userDAO.findAllByRoleCodeOrderByIdDesc(RoleCodeEnum.SUBJECT_ACCOUNT.getCode());
        List<SubjectAccountVO> accountList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            accountList = list.stream().map(e -> {
                SubjectAccountVO subjectAccount = new SubjectAccountVO();
                subjectAccount.setId(e.getUserId());
                subjectAccount.setName(e.getUserName());
                subjectAccount.setPhoto(e.getPhoto());
                return subjectAccount;
            }).collect(Collectors.toList());
        }
        redisUtil.set(key, JsonUtil.toJsonString(accountList), RedisKeyEnum.SUBJECT_ACCOUNT_LIST_CACHE.getExpireTime());
        return accountList;
    }
}
